package com.canyou.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.system.entity.role.RoleMenuDTO;
import com.canyou.system.mapper.RoleMapper;
import com.canyou.system.model.Role;
import com.canyou.system.model.RoleDept;
import com.canyou.system.model.RoleMenu;
import com.canyou.system.service.RoleDeptService;
import com.canyou.system.service.RoleMenuService;
import com.canyou.system.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 角色管理服务实现类
 *
 * @author canyou
 * @since 2019-05-14
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RoleDeptService roleDeptService;

    @Override
    public IPage<Role> getPageList(IPage<Role> page, String roleName) {
        return baseMapper.getPageList(page, roleName);
    }

    @Override
    public boolean existRole(String roleName, Long roleId) {
        LambdaQueryWrapper<Role> queryWrapper = Wrappers.<Role>lambdaQuery()
                .eq(Role::getRoleName, roleName);
        if (roleId != null) {
            queryWrapper.ne(Role::getId, roleId);
        }
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean saveRoleMenu(RoleMenuDTO roleMenuVO) {
        final Long roleId = roleMenuVO.getRoleId();
        roleMenuService.remove(Wrappers.<RoleMenu>lambdaUpdate().eq(RoleMenu::getRoleId, roleId));

        return roleMenuService.saveBatch(Arrays.stream(roleMenuVO.getMenuIds())
                .map(menuId -> new RoleMenu().setMenuId(menuId).setRoleId(roleId))
                .collect(Collectors.toList()));
    }

    @Override
    public boolean existRoleUser(Long roleId) {
        return baseMapper.getUserCountByRoleId(roleId) > 0;
    }

    @Override
    public boolean removeById(Long roleId) {
        return baseMapper.deleteById(roleId) > 0;
    }

    @Override
    public boolean removeRoleById(Long roleId) {
        roleMenuService.remove(Wrappers.<RoleMenu>lambdaUpdate().eq(RoleMenu::getRoleId, roleId));
        roleDeptService.remove(Wrappers.<RoleDept>lambdaUpdate().eq(RoleDept::getRoleId, roleId));
        return removeById(roleId);
    }

}
